package com.icss.trans.accept.httppoll;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icss.trans.cfg.BaseProperties;
import com.icss.trans.exception.TransException;
import com.icss.trans.util.XmlUtil;

/**
 * 
 * @ClassName: HttpConnector
 * @Description:
 * @author ICSS
 * @date 2015-3-25 下午2:41:58
 * 
 */
public class HttpAccepter {

    protected static Logger logger = LoggerFactory.getLogger(HttpAccepter.class);

    public HttpAccepter() {
    }

    /**
     * 
     * @Description: 接收处理文件
     * @param acceptParam
     * @param analyzeFile
     * @throws Exception
     */
    public static void accept(AcceptParam acceptParam, IAnalyzeFile analyzeFile) throws Exception {
        List<AcceptFileInfo> fileList = acceptFileList(acceptParam);
        for (AcceptFileInfo acceptFileInfo : fileList) {
            acceptParam.setFileName(acceptFileInfo.getName());
            acceptData(acceptParam, analyzeFile);
        }
    }

    /**
     * @throws Exception
     * 
     * @Description: 获取请求的文件列表。
     * @param acceptParam
     * @return
     * @throws
     */
    @SuppressWarnings("unchecked")
    public static List<AcceptFileInfo> acceptFileList(AcceptParam acceptParam) throws TransException {
        long startTime = System.currentTimeMillis();
        List<AcceptFileInfo> resultlList = new ArrayList<AcceptFileInfo>();
        HttpEntity formEntity;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = null;
        try {
            formEntity = new UrlEncodedFormEntity(acceptParam.buildNameValuePair(), "UTF-8");
            String sendUrl = BaseProperties.getInstance().getTransUrl();
            post = new HttpPost(sendUrl + "/getFileListInfo");
            post.setEntity(formEntity);
            logger.debug("acceptFileList:AcceptParam:" + acceptParam.toString());
            HttpResponse response = httpClient.execute(post);
            // 从response中取出HttpEntity对象
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                String strResult = EntityUtils.toString(response.getEntity(), "UTF-8");
                Document doc = XmlUtil.readConfig(strResult);
                List<Element> nodeList = doc.selectNodes("/files/file");
                AcceptFileInfo fileInfo = null;
                for (Element fileNode : nodeList) {
                    fileInfo = buildFileInfoFromXmlEle(fileNode);
                    resultlList.add(fileInfo);
                }
                logger.debug("acceptFileList ok!used time:" + (System.currentTimeMillis() - startTime));
            } else {
                logger.warn("accept data list error!!:statusCode:" + statusCode + "[" + acceptParam.getDataTransType()
                        + "]");
            }
        } catch (Exception e) {
            logger.error("accept data list from ei error!" + e.getMessage() + "[" + acceptParam.toString() + "][ "
                    + post.getURI() + "]", e);
            throw new TransException("http acceptFileList error：" + e.getMessage(), e);
        } finally {
            post.releaseConnection();
            httpClient.getConnectionManager().shutdown();
            post = null;
            httpClient = null;
        }
        return resultlList;
    }

    /**
     * @Description:
     * @param fileNode
     * @return
     * @throws
     */
    private static AcceptFileInfo buildFileInfoFromXmlEle(Element fileNode) {
        AcceptFileInfo fileInfo;
        fileInfo = new AcceptFileInfo();
        fileInfo.setName(fileNode.selectSingleNode("fileName").getText());
        fileInfo.setSize(fileNode.selectSingleNode("fileSize").getText());
        return fileInfo;
    }

    /**
     * 
     * @Description: 从EI接受文件数据。
     * @param acceptParam
     * @return
     * @throws Exception
     * @throws
     */
    public static void acceptData(AcceptParam acceptParam, IAnalyzeFile analyzeFile) throws TransException {
        HttpEntity formEntity;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = null;
        try {
            formEntity = new UrlEncodedFormEntity(acceptParam.buildNameValuePair(), "UTF-8");
            String sendUrl = BaseProperties.getInstance().getTransUrl();
            post = new HttpPost(sendUrl + "/downloadFile");
            post.setEntity(formEntity);
            logger.debug("acceptData:AcceptParam:" + acceptParam.toString());
            HttpResponse response = httpClient.execute(post);
            // 从response中取出HttpEntity对象
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                InputStream data = response.getEntity().getContent();

                analyzeFile.execute(acceptParam.getFileName(), data);
            }
        } catch (Exception e) {
            logger.error(
                    "accept data from ei error!" + e.getMessage() + "[" + acceptParam.toString() + "][ "
                            + post.getURI() + "]", e);
            throw new TransException("http acceptData error：" + e.getMessage(), e);
        } finally {
            post.releaseConnection();
            httpClient.getConnectionManager().shutdown();
            post = null;
            httpClient = null;
        }
    }

}
